package com.effectiv.gooruda.mvc.controller;


import javax.validation.Valid;

import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RequestParam;


import com.effectiv.gooruda.business.api.ApplicationService;
import com.effectiv.gooruda.business.api.SocialProviderService;
import com.effectiv.gooruda.domain.Application;
import com.effectiv.gooruda.domain.SocialProvider;
import com.effectiv.gooruda.mvc.argumentresolver.AjaxResponse;



@Slf4j
@Controller
public class SocialProviderContoller {
		
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private SocialProviderService socialProviderService;
	
	@RequestMapping(value = "/newsocialprovider")
	public final String newSocialProvider(@RequestParam(value="application", required=false) String appId, 
			@RequestParam(value="type") String type, 
			Model model) {
		
		SocialProvider provider = BeanUtils.instantiate(SocialProvider.class);
		provider.setType(type);
		
		if(StringUtil.isNotBlank(appId)){
			Application application = applicationService.findOne(appId);
			model.addAttribute("app",application);
		}
		
		model.addAttribute(provider);
		return "newsocialprovider";
	}
	
	
	@RequestMapping(value = "/saveprovider", method = RequestMethod.POST)
	public @ResponseBody
	AjaxResponse save(@Valid SocialProvider provider, BindingResult result,@RequestParam(value="app", required=false) String appId, 
			AjaxResponse response) {
		
		log.info("Application id = {}",appId);
		
		if (!result.hasErrors()) {
			socialProviderService.save(provider);
			
			if(StringUtil.isNotBlank(appId)){
				applicationService.addSocialProvider(appId, provider);
			}
			response.setResult(provider);
		} else {

			response.markValidationFailure(result.getFieldErrors());
		}
		log.info("AjaxResponse = {}", response);
		return response;
	}
	
	@RequestMapping(value = "/listsocialproviders")
	public final String listApplications(@RequestParam(value="type") String type, Model model) {
		log.info("Type = {}", type);
		
		model.addAttribute("providers", socialProviderService.findByType(type));	
		return "listsocialproviders";
	}
	
}
